package pers.whj.rpc.transport;

import pers.whj.rpc.common.Config;

import java.io.IOException;
import java.io.InputStream;

/**
 * 数据传输工具类
 */
public class TransportUtils {

    /**
     * 指定输入流，读取指定长度的数据
     *
     * @param input  输入流
     * @param length 目标长度
     * @return 字节数组
     * @throws IOException IO异常
     */
    public static byte[] readData(InputStream input, int length) throws IOException {
        byte[] data = new byte[length];
        int receive = 0;
        int maxLength = Config.MAX_LENGTH_ONCE;
        while (length > maxLength) {
            readData(input, data, receive, maxLength);
            receive += maxLength;
            length -= maxLength;
        }
        readData(input, data, receive, length);
        return data;
    }

    /**
     * 从输入流，读取指定长度数据到指定数组
     *
     * @param input  流
     * @param data   数组
     * @param offset 偏移
     * @param length 长度
     * @throws IOException IO异常
     */
    public static void readData(InputStream input, byte[] data, int offset, int length) throws IOException {
        int receive = 0;
        while (length > 0) {
            int len = input.read(data, offset + receive, length);
            receive += len;
            length -= len;
        }
    }
}
